const http=require('http')
const fs=require('fs')
const path=require('path')

var pagePath=path.join(__dirname,'/index.html')
var iconPath=path.join(__dirname,'/icon.png')
var pathName=''
var args=''
var argObj={}

function createTime(ctimeMs){
    var date1=new Date(ctimeMs);
    var year=date1.getFullYear();
    var month=date1.getMonth()+1;
    var day=date1.getDate();
    var hour=date1.getHours();
    var minute=date1.getMinutes();
    var second=date1.getSeconds()
    return year+'-'+month+'-'+day+"  "+hour+':'+minute+':'+second
}


//转换url
function parseUrl(urlStr){
    var index=urlStr.indexOf('?')
    if(index==-1){
        pathName=urlStr
    }else{
        pathName=urlStr.slice(0,index)
        args=urlStr.slice(index+1)
        var argArr=args.split('&')
        
        for(var i=0;i<argArr.length;i++){
            // 将等号两端的数据分割开，左边的是属性名，右边的是属性值
            argObj[argArr[i].split('=')[0]]=argArr[i].split('=')[1]
        }
    }
    return {
        pathName:pathName,
        argObj:argObj
    }
}


function router(urlObj,req,res){
    //如果有图片资源，则设置一个资源路径
    if(urlObj.pathName.indexOf('.png')>0 || urlObj.pathName.indexOf('.jpg')>0){
        urlObj.pathName='getimgdata';
    }
    switch(urlObj.pathName){
        case '/':
            showIndex(res);
            break;
        case 'getimgdata':
            resImage(res);
            break;
        case '/getlist':
            showList(res);
            break;
        case '/del':
            deleteFile(urlObj.argObj,res);
            break;
    }
}

function showIndex(res){
    var fileContent=fs.readFileSync(pagePath)
    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})
    // 响应请求，向前端发送数据
    res.write(fileContent)
    res.end()
}

function resImage(res){
    var imgContent=fs.readFileSync(iconPath)
    res.writeHead(200,{'Content-Type':'image/png'})
    res.write(imgContent)
    res.end()
}

function showList(res){
    var dirPath=path.join(__dirname,'/fileDir')
    var files=fs.readdirSync(dirPath)
    var fileList=[]
    for(var i=0;i<files.length;i++){
        var filePath=path.join(dirPath,'/'+files[i]);
        var fileObj=fs.statSync(filePath)
        var obj={};
        obj.fileName=files[i];
        obj.fileTime=createTime(fileObj.ctimeMs);
        // obj.fileTime=fileObj.ctimeMs;
        obj.fileSize=fileObj.size;
        obj.fileType=fileObj.isFile() ? 'file' : 'folder';
        fileList.push(obj)
    }
    var jsonStr=JSON.stringify(fileList)
    res.writeHead(200,{'Content-Type':'text/plain'})
    res.write(jsonStr)
    res.end()
}

function deleteFile(argObj,res){
    var delId=argObj.delId;
    console.log(argObj)
    var dirPath=path.join(__dirname,'/fileDir')
    var files=fs.readdirSync(dirPath)
    for(var i=0;i<files.length;i++){
        var fileObj=fs.statSync(path.join(dirPath,'/'+files[i]))
        if(delId.indexOf(fileObj.ctimeMs)>0){
            fs.unlinkSync(path.join(dirPath,'/'+files[i]))
            res.end('success')
            break
        }
    }
}

http.createServer((req,res)=>{
    // http://localhost:8081/pathname/?delId=123
    // 协议名   端口号        资源路径     参数
    // req.url指端口或域名之后的部分：/pathname/?delId=123&pageId=10
    var urlStr=req.url;
    var urlObj=parseUrl(urlStr)
    router(urlObj,req,res)

}).listen(8081)


console.log('server is listening 8081')


/*
1、在nodejs搭建服务器，监听客户端的请求，根据url的不同相应不同的数据
2、响应的数据来自nodejs对文件系统的访问
*/